package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"news_sys/models"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var user models.User
	user.UserAccount = c.GetString("account")
	Password := c.GetString("password")
	key := fmt.Sprintf("account:%s", user.UserAccount)
	count, _ := models.RDB.Get(models.Ctx, key).Int()
	if count > 2 {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "密码错误三次，锁定账号两小时",
		}
		c.ServeJSON()
		return
	}
	if user.GetUserByUserAccount() != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "账号不存在",
		}
		c.ServeJSON()
		return
	}
	if models.MD5(Password) != user.UserPassword {
		models.RDB.Incr(models.Ctx, key)
		if count == 2 {
			models.RDB.Expire(models.Ctx, key, 2*time.Hour)
		}
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "密码错误请重试",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "登陆成功",
		"Data": user.ID,
	}
	c.ServeJSON()
	return
}
